package com.allen.retrofit2_rxjava2.view.selectImage;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.AppCompatCheckBox;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.allen.retrofit2_rxjava2.R;
import com.allen.retrofit2_rxjava2.base.TitleViewActivity;
import com.allen.retrofit2_rxjava2.view.selectImage.adapter.GalleryAdapter;
import com.allen.retrofit2_rxjava2.view.selectImage.adapter.UploadVideoImageAdapter;
import com.allen.retrofit2_rxjava2.view.selectImage.entity.ChooseUploadParam;
import com.allen.retrofit2_rxjava2.view.selectImage.utils.SizeUtils;
import com.allen.retrofit2_rxjava2.view.selectImage.view.GridItemDecoration;
import com.allen.retrofit2_rxjava2.view.selectimageview.PhotoActivity;
import com.allen.retrofit2_rxjava2.view.selectimageview.utils.CameraUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Iterator;

public class SelectPhotoActivity extends TitleViewActivity implements View.OnClickListener, UploadVideoImageAdapter.OnItemClickListener, GalleryAdapter.OnItemCblickListener {

    private static final String TAG = "photoActivity";
    private static final int MSG_SUCCESS = 1;
    private static final int MSG_FAILED = 0;
    public static final int REQUEST_PHONE = 299;

    private TextView tv_preview;
    private ArrayList<ChooseUploadParam> params;
    private ArrayList<ChooseUploadParam> selectingParams;
    private ScanHandler handler;
    //还能上传的最大文件数
    private int maxLeftCount;
    private RelativeLayout rl_bottom;
    private GalleryAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gallery);
        initTitleBar();
        initView();
        initData();
    }

    private void initTitleBar() {
        initTitleView();
        initLeftBackView(null);
        setRightViewVisible(false);
        setCenterViewContent(getResources().getString(R.string.select_image));
        initRightView(getResources().getString(R.string.add));
        setRightViewOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                send();//发送
            }
        });
    }

    private void initView() {
        rl_bottom = (RelativeLayout) findViewById(R.id.rl_bottom);
        tv_preview = (TextView) findViewById(R.id.tv_preview);
        tv_preview.setOnClickListener(this);
        tv_preview.setText("预览");
        tv_preview.setEnabled(false);
    }

    private void initData() {
        params = new ArrayList<>();
        selectingParams = new ArrayList<>();
        WeakReference<SelectPhotoActivity> reference = new WeakReference<>(SelectPhotoActivity.this);
        handler = new ScanHandler(reference);
        Intent intent = getIntent();
        maxLeftCount = intent.getIntExtra("maxLeftCount", 3);
        new Thread(new ScanRunnable()).start();
    }

    private void initGallery() {
        RecyclerView rv_gallery = (RecyclerView) findViewById(R.id.rv_gallery);
        rv_gallery.setLayoutManager(new GridLayoutManager(this, 3));
        rv_gallery.setItemAnimator(new DefaultItemAnimator());
        int px = SizeUtils.dp2px(this, 3);
        rv_gallery.addItemDecoration(new GridItemDecoration(px));
        adapter = new GalleryAdapter(this, params);
        adapter.setOnItemClickListener(this);
        adapter.setOnItemCblickListener(this);
        rv_gallery.setAdapter(adapter);
    }

    @Override
    public void onItemClick(int position, int viewType, ChooseUploadParam param) {
//        preview(position);
    }

    @Override
    public void onItemCbClick(int position, ChooseUploadParam param, CheckBox cb) {
        if (cb.isChecked()) {
            selectingParams.add(param);

            if (selectingParams.size() > maxLeftCount) {
                removeParam(param);
                cb.toggle();
                Toast.makeText(this, "最多只允许上传3张图片", Toast.LENGTH_SHORT).show();
                return;
            }
        } else {
            removeParam(param);
        }
        setText();
    }

    private void removeParam(ChooseUploadParam param) {
        Iterator<ChooseUploadParam> iterator = selectingParams.iterator();
        while (iterator.hasNext()) {
            if (param.getPath().equals(iterator.next().getPath())) {
                iterator.remove();
            }
        }
    }

    //扫描本地视频和图片
    class ScanRunnable implements Runnable {

        @Override
        public void run() {
            //不要视频文件
//            query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
//                    MediaStore.Video.Media.DATE_MODIFIED, MediaStore.Video.Media.DATA);
            query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    MediaStore.Images.Media.DATE_MODIFIED, MediaStore.Images.Media.DATA);
            Message msg = handler.obtainMessage();
            if (params.size() <= 0) {
                msg.what = MSG_FAILED;
            } else {
                msg.what = MSG_SUCCESS;
            }
            msg.sendToTarget();
        }

        private void query(Uri uri, String sortOrder, String columnName) {
            Cursor cursor = getContentResolver().query(uri, null, null, null, sortOrder);
            if (cursor == null) {
                Log.e(TAG, uri.getPath() + "------cursor为null");
                return;
            }
            while (cursor.moveToNext()) {
                String path = cursor.getString(cursor.getColumnIndex(columnName));
                if (TextUtils.isEmpty(path)) {
                    continue;
                }
                File file = new File(path);
                if (!file.exists()) {
                    continue;
                }
                if (file.length() == 0) {
                    continue;
                }
                Log.d(TAG, path);
                ChooseUploadParam param = new ChooseUploadParam();
                if (uri.equals(MediaStore.Video.Media.EXTERNAL_CONTENT_URI)) {
                    handleVideoThumbnail(path);
                    param.setType(UploadVideoImageAdapter.TYPE_VIDEO);
                } else {
                    param.setType(UploadVideoImageAdapter.TYPE_IMG);
                }
                param.setPath(path);
                params.add(param);
            }
            cursor.close();
        }
    }

    private static class ScanHandler extends Handler {

        private WeakReference<SelectPhotoActivity> reference;

        public ScanHandler(WeakReference<SelectPhotoActivity> reference) {
            this.reference = reference;
        }

        @Override
        public void handleMessage(Message msg) {
            if (reference == null) {
                return;
            }
            SelectPhotoActivity object = reference.get();
            if (object == null) {
                return;
            }
            object.handleMessage(msg);
        }
    }

    private void handleMessage(Message msg) {
        switch (msg.what) {
            case MSG_SUCCESS:
                initGallery();
                break;
            case MSG_FAILED:
                Toast.makeText(this, "获取本地图片失败!", Toast.LENGTH_SHORT).show();
                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.tv_preview:
                preview();//预览
                break;
            default:
                finish();
                break;
        }
    }

    private void send() {
        Intent intent = new Intent();
        intent.putParcelableArrayListExtra("data", selectingParams);
        if (selectingParams.size() == 0) {
            setResult(RESULT_CANCELED, intent);
        } else {
            setResult(RESULT_OK, intent);
        }
        finish();
    }

    //点击预览按钮的预览
    private void preview() {
        Intent intent = new Intent(this, PreviewUploadActivity.class);
        intent.putParcelableArrayListExtra("data", selectingParams);
        intent.putParcelableArrayListExtra("select", selectingParams);
        intent.putExtra("maxLeftCount", maxLeftCount);
        intent.putExtra("initPosition", 0);
        startActivityForResult(intent, REQUEST_PHONE);
    }

    //点击图片的预览

    /**
     * @param position 有个bug
     *                 Binder传输的数据太大导致的异常。
     *                 如果Binder的参数或返回值太大，不适合的事务缓冲区，
     *                 然后调用将失败，并将被抛出TransactionTooLargeException。
     *                 解决方法：不要将大量数据传入Binder
     *                 TransactionTooLargeException
     */
    private void preview(int position) {
//        Intent intent = new Intent(this, FeedbackPreviewActivity.class);
//        intent.putParcelableArrayListExtra("data", params);
//        intent.putParcelableArrayListExtra("select", selectingParams);
//        intent.putExtra("maxLeftCount", maxLeftCount);
////        intent.putExtra("hasVideo", hasVideo);
//        intent.putExtra("initPosition", position);
//        startActivityForResult(intent, REQUEST_PHONE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.d(TAG, data + ":" + (resultCode == RESULT_OK));
        if (resultCode == RESULT_OK) {
            setResult(resultCode, data);
            finish();
        }
        if (resultCode == REQUEST_PHONE) {
            ArrayList<ChooseUploadParam> params = data.getParcelableArrayListExtra("data");
            adapter.setCbSelected(params);
            selectingParams.clear();
            selectingParams.addAll(params);
            setText();
        }

    }

    //检测sd卡是否可用
    private boolean checkSDcardValid() {
        String sdStatus = Environment.getExternalStorageState();
        if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) {
            Toast.makeText(this, " sd卡不可用！", Toast.LENGTH_LONG).show();
            return false;
        }
        return true;
    }

    //判断文件夹是否创建成功
    private boolean createDir() {
        File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/demo/Camera/");
        Log.d(TAG, "文件夹路径：" + dir.getAbsolutePath());
        if (!dir.exists()) {
            if (!dir.mkdir()) {
                Log.e(TAG, "创建文件夹失败！");
                return false;
            }
        }
        return true;
    }

    //保存视频缩略图到本地
    private void saveThumbnail(String videoPath) {
        if (!checkSDcardValid() || !createDir()) {
            return;
        }
        Bitmap thumbnail = ThumbnailUtils.createVideoThumbnail(videoPath, MediaStore.Video.Thumbnails.MINI_KIND);
        if (thumbnail == null) {
            Log.e(TAG, "要保存的缩略图为空！");
            return;
        }
        String picPath = videoPath.replace(".mp4", ".jpg");
        File f = new File(picPath);
        try {
            FileOutputStream out = new FileOutputStream(f);
            thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, out);
            out.flush();
            out.close();
            Log.d(TAG, "保存缩略图成功！");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void handleVideoThumbnail(String path) {
        String suffix = path.substring(path.indexOf("."));
        String thumbnailPath = path.replace(suffix, ".jpg");
        File file = new File(thumbnailPath);
        if (!file.exists()) {
            saveThumbnail(path);
        }
    }

    private void setText() {
        String text_send = "添加(" + selectingParams.size() + "/" + maxLeftCount + ")";
        String text_preview = "预览(" + selectingParams.size() + ")";
        if (selectingParams.size() == 0) {
            rl_bottom.setVisibility(View.GONE);
            text_send = "添加";
            text_preview = "预览";
            setRightViewVisible(false);
            tv_preview.setEnabled(false);
        } else {
            rl_bottom.setVisibility(View.VISIBLE);
            setRightViewVisible(true);
            tv_preview.setEnabled(true);
        }
        initRightView(text_send);
        tv_preview.setText(text_preview);
    }
}
